<?php

include_once __DIR__."/db.class.php";

class User
{
	/* private $username; */
	/* private $password; */
	/* private $user_id; */
	/* private $status = false; */
	/* private $login_time; */

	/* function __construct($username, $password) */
	/* { */
	/* 	$this -> username = $username; */
	/* 	$this -> password = md5($password); */
		
	/* } */
	public static $user_online;

	function __construct()
	{
		self::$user_online = count($this -> get_online_user());
	}

	public function is_user($username)
	{
		$connect = new Connect();
		$action = $connect -> connect_db() -> prepare("select password from users where username = ?");
		$action -> execute(array($username));
		$result = $action -> fetchAll();
		if(count($result) === 0)
		{
			return false;
		}
		else
		{
			return $result[0]['password'];
		}
	}

	public function is_legal($username, $password)
	{
		$config = $this -> is_user($username);
		if($config === false)
		{
			return false;
		}
		elseif(md5($password) !== $config)
		{
			return false;
		}
		else
		{
			return true;
		}
	}

	public function set_online($user_id)
	{
		$connect = new Connect();
		$action = $connect -> connect_db() -> prepare("update users set users.on=1, users.last_login = ? where user_id = ?");
		$login_time = date("Y:m:d H:i:s");
		$action -> execute(array($login_time, $user_id));
	}

	public function set_offline($user_id)
	{
		$connect = new Connect();
		$action = $connect -> connect_db() -> prepare("update users set users.on=0 where user_id = ?");
		$action -> execute(array($user_id));
	}

	public function set_user_online_sum($user_id, $sum)
	{
		$connect = new Connect();
		$action = $connect -> connect_db() -> prepare("update users set users.user_online = ? where user_id = ?");
		$action -> execute(array($sum, $user_id));
	}

	public function is_online($user_id)
	{
		$connect = new Connect();
		$action = $connect -> connect_db() -> prepare("select on from users where user_id = ?");
		$action -> execute(array($user_id));
		$result = $action -> fetchAll();
		return $result[0]['on'];
	}

	public function get_user_id($username)
	{
		$connect = new Connect();
		$action = $connect -> connect_db() -> prepare("select user_id from users where username = ?");
		$action -> execute(array($username));
		$result = $action -> fetchAll();
		return $result[0]['user_id'];
	}

	public function get_online_user()
	{
		$connect = new Connect();
		$action = $connect -> connect_db() -> prepare("select username from users where users.on = 1");
		$action -> execute();
		$result = $action -> fetchAll();
		return $result;
	}

	public function get_user_online_sum($user_id)
	{
		$connect = new Connect();
		$action = $connect -> connect_db() -> prepare("select user_online from users where user_id = ?");
		$action -> execute(array($user_id));
		$result = $action -> fetchAll();
		return $result[0]['user_online'];
	}

}
?>
